//
//  PSBadge.m
//  PSControls
//
//  Created by Matias Ginart on 11/04/11.
//  Copyright 2011 Casa. All rights reserved.
//

#import "PSBadge.h"
#import "PSBadgePool.h"

@implementation PSBadge

@synthesize reuseWhenRemovedFromSuperview;

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        reuseWhenRemovedFromSuperview = YES;

        UIImageView* backgroundImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"BadgeBackground.png"]];
        backgroundImage.frame = self.bounds;
        backgroundImage.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        backgroundImage.contentMode = UIViewContentModeScaleToFill;
        [self addSubview:backgroundImage];
        [backgroundImage release];

        badgeLabel = [[UILabel alloc] initWithFrame:self.bounds];
        badgeLabel.backgroundColor = [UIColor clearColor];
        badgeLabel.textAlignment = UITextAlignmentCenter;
        badgeLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        badgeLabel.font = [UIFont systemFontOfSize:13];
        [self addSubview:badgeLabel];
    }
    return self;
}

#pragma mark - Setters and getters

- (void)setValue:(NSInteger)badge {
    NSString* text = [[NSString alloc] initWithFormat:@"%d",badge];
    badgeLabel.text = text;
    [text release];
}

- (NSInteger)value {
    return [badgeLabel.text integerValue];
}

#pragma mark - Inherited Methods

- (void)removeFromSuperview {
    if (reuseWhenRemovedFromSuperview) {
        [self isReadyToReuse];
    }
    [super removeFromSuperview];
}

#pragma mark - Methods

- (void)isReadyToReuse {
    PSBadgePool* pool = [PSBadgePool sharedBadgePool];
    [pool badgeViewIsReadyToBeReused:self];
}

#pragma mark - Memory

- (void)dealloc {
    [badgeLabel release];
    [super dealloc];
}

@end
